import numbers
class Field:
    pass

class IntField(Field):
    def __init__(self,name,min=None,max=None):
        self.name = name
        self.min = min
        self.max = max
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = value

class CharField(Field):
    def __init__(self,name,max_length):
        self.name = name
        if isinstance(max_length,numbers.Integral):
            self.max_length = max_length
        else:
            raise ValueError('max_length must be number')
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        if isinstance(value,str):
            if len(value)> self.max_length:
                raise ValueError("the length of value is too long")
            self.value = value
        else:
            raise ValueError("value must be str type")

class OrmMeta(type):
    #可以使用拆包方式将参数args解析为 name,bases,attrs
    #def __new__(cls, *args, **kwargs):
    def __new__(cls, name,bases,attrs, **kwargs):
        fields = {}
        #将属性描述符字段解析出来
        for k,v in attrs.items():
            if isinstance(v,Field):
                fields[k] = v
        _meta = {}
        attrs_meta = attrs.get("Meta",None)
        table = None
        if attrs_meta:
            table = getattr(attrs_meta,"table")
        if not table:
            table = name.lower()
        _meta["table"] = table
        #这里将Fields和meta信息注入到 User类的attrs字典中
        attrs["fields"] = fields
        attrs["_meta"] = _meta
        if "Meta" in attrs:
            del attrs["Meta"]
        return super().__new__(cls,name,bases,attrs,**kwargs)


#进一步优化提取公共操作到基类
class Model(metaclass=OrmMeta):
    def __init__(self,*args,**kwargs):
        for name,value in kwargs.items():
            setattr(self,name,value)
        super().__init__()
    def save(self):
        fields = []
        values = []
        for k,v in self.fields.items():
            fields.append(v.name)
            if isinstance(v.value,str):
                values.append("'"+v.value+"'")
            else:
                values.append(str(v.value)) # 这里强制转换为str
        sql = f"insert into {self._meta.get('table')}({','.join(fields)}) values({','.join(values)})"
        #注意，这个经典错误,join要求数据类型都是str, {TypeError}sequence item 1: expected str instance, int found
        print(sql)
class User(Model):
    name = CharField('name',6)
    age = IntField('age',1,100)

    class Meta:
        table = 't_user'

user = User(name="caoyx",age=42)
user.save()
pass